package com.ltmonitor.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ltmonitor.entity.*;
import com.ltmonitor.service.IUserPreferenceService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.service.IRoleService;
import com.ltmonitor.service.IUserInfoService;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用户信息编辑更新，修改密码
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/user")
public class UserAction extends PaginateAction {
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IUserPreferenceService userPreferenceService;

	@Autowired
	private IRoleService roleService;
	// 用户选择的多个部门车组ID，用逗号隔开,如1，21，34的形式
	private String strDepId;

	@RequestMapping("/viewList.action")
	public String list() {
		return "/user/userList";
	}

	@RequestMapping("/view.action")
	public String view(
			Model m,
			@RequestParam(value = "entityId", required = false, defaultValue = "0") long id) {
		long roleId = 0;// 用户分配的角色Id
		try {
			if (id > 0) {
				UserInfo user = this.userInfoService.load(id);
				m.addAttribute("entity", user);
				if (user.getEntityId() > 0) {
					Role r = user.getRole();
					if (r != null)
						roleId = r.getEntityId(); // 用于页面显示用户已经分配的角色
				}
			} else {
				UserInfo user = new UserInfo();
				m.addAttribute("entity", user);
			}
			// m.addObject("message", "保存成功");

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", "发生错误:" + ex.getMessage());
		}
		m.addAttribute("roleId", roleId);
		return "/user/editUser";
	}

	@RequestMapping("/viewMyPassword.action")
	public String viewMyPassword() {
		return "/user/updatePassword";
	}

	/**
	 * 用户更改自己的密码
	 * 
	 * @return
	 */
	@RequestMapping("/updatePassword.action")
	public String updatePassword(String oldPsd, String newPsd, Model m) {

		OnlineUser onlineUser = getOnlineUser();
		if (onlineUser != null) {
			UserInfo user = (UserInfo) this.userInfoService.load(onlineUser
					.getEntityId());
			if (user.getPassword().equals(oldPsd)) {
				user.setPassword(newPsd);
				userInfoService.update(user);
				m.addAttribute("message", "修改成功");
			} else if(oldPsd!=null){
				m.addAttribute("message", "旧密码不正确");

			}
		}
		return "/user/updatePassword";
	}

	@RequestMapping("/save.action")
	public String save(long entityId, Model m, String strDepId, long roleId) {
		UserInfo user = new UserInfo();
		m.addAttribute("roleId", roleId); //保存后，提供给页面获取
		try {
			if(entityId > 0)
			{
				user = this.userInfoService.load(entityId);
			}
			try {
				BeanUtils.copyProperties(user, super.getParams());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				m.addAttribute("message", "录入数据转换错误");
				m.addAttribute("entity", user);
				return "/user/editUser";
			}
			String hql = "from UserInfo where loginName = ? and deleted = ? and entityId <> ?";
			UserInfo otherUser = (UserInfo) this.userInfoService.find(
					hql,
					new Object[] { user.getLoginName(), false,
							user.getEntityId() });
			if (otherUser != null) {
				m.addAttribute("message", "用户登录名已经存在，请重选输入");
				m.addAttribute("entity", user);
				return "/user/editUser";
			}
			if (user.getCompanyId() == 0) {
				m.addAttribute("message", "请选择用户所属企业!");
				m.addAttribute("entity", user);
				return "/user/editUser";
			}
			if ("clear".equals(strDepId)) {
				user.getDepartments().clear();
			} else if (strDepId != null && strDepId.length() > 0) {

				user.getDepartments().clear();
				String[] depIdArray = strDepId.split(",");
				for (String str : depIdArray) {
					if (str != null && str.length() > 0) {
						long depId = Long.parseLong(str);
						if (depId > 0) {
							Department dep = (Department) this.departmentService
									.load(depId);
							user.getDepartments().add(dep);
						}
					}
				}
			}
			if (roleId > 0) {
				// 分配角色
				Role r = user.getRole();
				if (r == null || r.getEntityId() != roleId) {
					user.getRoles().clear();
					r = this.roleService.load(roleId);
					user.getRoles().add(r);
				}
			}
			this.userInfoService.saveOrUpdate(user);
			m.addAttribute("message", "保存成功!");
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", "保存失败:" + ex.getMessage());
		}
		m.addAttribute("entity", user);
		return "/user/editUser";
	}

	/**
	 * 假删除，通过更新数据库的删除标记
	 * @param request
	 * @param model
	 * @param id 实体类ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/fakeDelete.action")
	public JsonMessage fakeDelete(HttpServletRequest request, Model model,
			@RequestParam(value = "entityId") Long id) {

		try {
			UserInfo u = this.userInfoService.load(id);
			if(u != null && u.isSuperAdmin())
			{
				return jsonFail("系统内置超级用户不能被删除!");
			}
			this.userInfoService.deleteFakeById(id);
			return jsonSuccess("记录已被成功刪除!");

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return jsonFail(ex.getMessage());
		}

	}
	/**
	 * 设置地图中心
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/setMapCenter.action")
	public JsonMessage setMapCenter(double lat, double lng, int zoom,
			String mapType) {
		try {
			OnlineUser onlineUser = this.getOnlineUser();
			if (onlineUser != null) {
				UserInfo user = (UserInfo) this.userInfoService.load(onlineUser
						.getEntityId());
				user.setMapCenterLng(lng);
				user.setMapCenterLat(lat);
				user.setMapLevel(zoom);
				this.userInfoService.saveOrUpdate(user);// 保存到用户信息中
				// this.setOnlineUser(user);
				/**
				 * SystemConfig sc = (SystemConfig) getSession().get(
				 * "systemConfig"); if (sc != null) { sc.setInitLat(lat);
				 * sc.setInitLng(lng); sc.setInitZoomLevel(zoom); }
				 */
				return json(true, "已设置为当前默认地图中心！");
			}
			return json(false, "网页过期，请重新登录!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}

	}

	/**
	 * 用户修改自己的地图类型
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/setMyMapType.action")
	public JsonMessage setMyMapType(String mapType) {
		try {
			OnlineUser onlineUser = this.getOnlineUser();
			if (onlineUser != null) {
				UserInfo user = (UserInfo) this.userInfoService.load(onlineUser
						.getEntityId());
				user.setMapType(mapType);
				this.userInfoService.saveOrUpdate(user);// 保存到用户信息中
				onlineUser.setMapType(mapType);
				// this.setOnlineUser(user);

				return json(true, "");
			}
			return json(false, "网页过期，请重新登录!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}

	}


	/**
	 * 保存用户选项
	 * @param uc
	 * @param m
	 * @return
	 */
	@RequestMapping("/savePreference")
	public String saveConfig(UserPreference uc, Model m) {
		try {
			uc.setUserId(this.getOnlineUser().getEntityId());
			this.userPreferenceService.saveOrUpdate(uc);
			this.putSession(SESSION_KEY_USER_PREFERENCE,uc);
			m.addAttribute("message", "保存成功");
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", ex.getMessage());
		}
		m.addAttribute("entity", uc);
		return "/user/editUserPreference";

	}

	@RequestMapping("/viewPreference.action")
	public ModelAndView view(Model model) {
		ModelAndView m = new ModelAndView();
		try {
			UserPreference uc = this.userPreferenceService.getUserPreferenceByUserId(this.getOnlineUser().getEntityId());
			if (uc == null) {
				uc = new UserPreference();
				uc.setUserId(this.getOnlineUser().getEntityId());
			}

			m.addObject("entity", uc);

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addObject("发生错误:"+ex.getMessage());
		}

		m.setViewName("/user/editUserPreference");
		return m;
	}

}